package mebp.genetic.selection;

import java.util.Random;

import mebp.genetic.Individuum;
import mebp.genetic.Population;
import mebp.genetic.recombination.RecombinationStrategy;

import org.apache.log4j.Logger;

public class LogSelection implements SelectionStrategy {
	
	Logger log = Logger.getLogger(LogSelection.class);

	float param=0.3f;
	Random rnd;
	
	/**
	 * 
	 * @param scale usually something between 0..1
	 * 			0 means equal distribution between good and bad samples
	 * 			1 leaves a kind of inverse-qubic distribution
	 */
	public LogSelection(float scale) {
		rnd=new Random(System.currentTimeMillis());
		param=scale;
	}

	public LogSelection() {
		rnd=new Random(System.currentTimeMillis());

	}

	/**
	 * Get next random
	 * @param max
	 * @return
	 */
	private int next(int max) {
		return (int)(rnd.nextDouble()*Math.pow(rnd.nextDouble(), param)*max  );
	}
	

	@Override
	public void selectionAndRecombination(Population population,
			Population nextgen, RecombinationStrategy recombination) {
		
		Individuum[] oldpop=population.getArray();
		int count=oldpop.length;
		
		while (nextgen.getSize()<count) {
			int index1=next(count);
			int index2=next(count);
			
			//log.trace("index selcted: "+index1+" ; "+index2);

			if (index2==index1) index2=(index2+1) % oldpop.length;
			nextgen.add(recombination.recombine(oldpop[index1],oldpop[index2]));
			
		}
	}

}
